<script setup lang="ts">
import { ref } from 'vue';
import { useBookStore } from '../stores/bookStore';

const store = useBookStore();
const isDragging = ref(false);
const fileInput = ref<HTMLInputElement>();

// 添加点击选择文件功能
const handleClick = () => {
  fileInput.value?.click();
};

// 添加文件选择处理
const handleFileSelect = (e: Event) => {
  const target = e.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file?.type !== 'text/plain') return;
  
  // 使用相同的文件读取逻辑
  readFileContent(file);
};

// 提取文件读取逻辑为独立函数
const readFileContent = (file: File) => {
  // 尝试多种编码方式读取文件
  const tryReadFile = (encoding: string) => {
    return new Promise<string>((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        
        // 计算编码质量分数
        const totalChars = result.length;
        const chineseChars = (result.match(/[\u4e00-\u9fa5]/g) || []).length;
        const garbledChars = (result.match(/[\uFFFD]/g) || []).length;
        
        // 计算质量分数：中文字符比例 - 乱码字符比例
        const quality = (chineseChars / totalChars) - (garbledChars / totalChars);
        
        console.log(`${encoding} 编码质量:`, {
          total: totalChars,
          chinese: chineseChars,
          garbled: garbledChars,
          quality: quality.toFixed(3)
        });
        
        // 如果质量分数大于0.1，认为编码成功
        if (result && quality > 0.1) {
          resolve(result);
        } else {
          reject(new Error(`Quality too low: ${quality.toFixed(3)}`));
        }
      };
      reader.onerror = () => reject(new Error('Read failed'));
      reader.readAsText(file, encoding);
    });
  };

  // 按优先级尝试不同编码
  const encodings = ['UTF-8', 'GBK', 'GB2312', 'GB18030', 'Big5'];
  
  const readWithEncoding = async () => {
    console.log('开始尝试不同编码读取文件:', file.name);
    
    for (const encoding of encodings) {
      try {
        console.log(`尝试编码: ${encoding}`);
        const content = await tryReadFile(encoding);
        console.log(`✅ 成功使用 ${encoding} 编码读取文件`);
        console.log('文件内容预览:', content.substring(0, 200));
        store.loadBook(content, file.name);
        return;
      } catch (error: any) {
        console.log(`❌ ${encoding} 编码失败:`, error.message);
        continue;
      }
    }
    
    // 如果所有编码都失败，尝试二进制读取
    console.log('⚠️ 所有编码都失败，尝试二进制读取');
    
    // 先尝试默认编码
    const defaultReader = new FileReader();
    defaultReader.onload = (e) => {
      const content = e.target?.result as string;
      console.log('默认编码读取结果:', content.substring(0, 200));
      
      // 如果默认编码结果很差，尝试强制使用GBK
      if (content.includes('')) {
        console.log('尝试强制使用GBK编码');
        const gbkReader = new FileReader();
        gbkReader.onload = (e2) => {
          const gbkContent = e2.target?.result as string;
          console.log('强制GBK编码结果:', gbkContent.substring(0, 200));
          store.loadBook(gbkContent, file.name);
        };
        gbkReader.readAsText(file, 'GBK');
      } else {
        store.loadBook(content, file.name);
      }
    };
    defaultReader.readAsText(file);
  };

  readWithEncoding();
};

const handleDrop = (e: DragEvent) => {
  e.preventDefault();
  isDragging.value = false;
  
  const file = e.dataTransfer?.files[0];
  if (file?.type !== 'text/plain') return;
  
  readFileContent(file);
};

const handleDragOver = (e: DragEvent) => {
  e.preventDefault();
  isDragging.value = true;
};

const handleDragLeave = () => {
  isDragging.value = false;
};
</script>

<template>
  <div 
    class="upload-area"
    :class="{ 'dragging': isDragging }"
    @dragover="handleDragOver"
    @dragleave="handleDragLeave"
    @drop="handleDrop"
    @click="handleClick"
  >
    <input 
      type="file" 
      ref="fileInput" 
      @change="handleFileSelect" 
      style="display: none;" 
    />
    <div class="upload-icon">
      <svg width="60" height="60" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M12 2L12 16M12 16L16 12M12 16L8 12" stroke="#fdd835" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M20 12V18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V12" stroke="#fdd835" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </div>
    <h2>拖拽或点击选择小说TXT文件</h2>
    <p>支持中文小说文本，点击区域即可选择文件</p>
  </div>
</template>

<style scoped>
.upload-area {
  border: 3px dashed #fff59d;
  border-radius: 30px;
  padding: 60px 40px;
  text-align: center;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  min-height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 8px 32px rgba(255, 245, 157, 0.15);
  border: 1px solid rgba(255, 245, 157, 0.2);
  animation: floatUp 1s ease-out;
}

.dragging {
  background: rgba(255, 253, 231, 0.9);
  transform: scale(1.02) translateY(-5px);
  box-shadow: 0 15px 40px rgba(255, 245, 157, 0.25);
  border-color: #fdd835;
}

.upload-icon {
  margin-bottom: 20px;
}

h2 {
  color: #8d6e63;
  margin: 15px 0;
  font-size: 1.8rem;
  font-weight: 600;
}

p {
  color: #a1887f;
  font-size: 1.1rem;
}

@keyframes floatUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
